package com.cqhz.quwan.ui.widget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.cqhz.quwan.R
import com.cqhz.quwan.model.NumType
import com.cqhz.quwan.ui.buy.adapter.BallAdapter
import com.cqhz.quwan.util.inflate
import com.cqhz.quwan.util.random

class NumberSelectorView(
        context: Context?, attrs: AttributeSet?
) : LinearLayout(context, attrs) {
    init {
        orientation = VERTICAL
    }
    private var changeListener:((ArrayList<ArrayList<Int>>)->Unit)? = null
    private var data = ArrayList<ArrayList<Int>>()
    private val adapters = ArrayList<BallAdapter>()
    private val bitLines = ArrayList<NumType.BitLine?>()
    fun setChangeListener(listener:(ArrayList<ArrayList<Int>>)->Unit){
        this.changeListener = listener
    }
    private fun addBitLine(bitLine: NumType.BitLine?,index:Int){
        val nsv = inflate(R.layout.layout_number_selector)
        val labelView = nsv.findViewById<TextView>(R.id.selector_label)
        val selectorNumGv = nsv.findViewById<AutoHeightGridView>(R.id.gv_selector_num)
        labelView?.text = bitLine?.label
        val adapter = BallAdapter(context,R.layout.item_red_ball)
        adapter.numberFormat = false
        adapter.listener = {
            data[index].clear()
            data[index].addAll(it.sorted())
            changeListener?.invoke(data)
        }
        adapter.selectMin = bitLine?.selectMin?:1
        adapter.selectMax = bitLine?.selectMax?:bitLine?.nums?.size?:0
        selectorNumGv.adapter = adapter
        bitLines.add(bitLine)
        adapters.add(adapter)
        adapter.setData(bitLine?.nums!!)
        adapter.setChecks(bitLine.selected)
        addView(nsv)
    }
    fun addBitLines(lines:List<NumType.BitLine?>?){
        if(lines == null){
          return
        }
        for ((index, line) in lines.withIndex()){
            data.add(ArrayList())
            addBitLine(line,index)
            if(index < lines.size-1){
                val lp = LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,5)
                val lineView = View(context)
                lineView.layoutParams = lp
                lineView.setBackgroundColor(0xFFF4F4F4.toInt())
                addView(lineView)
            }
        }
    }

    fun clearAllChecks(){
        for (adapter in adapters){
            adapter.clearChecks()
        }
    }

    fun randoms(){
        for (adapter in adapters){
            val randomNum = adapter.mData.random(adapter.selectMin)?.sorted()
            adapter.setChecks(randomNum)
        }
    }
}